﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LLR.LearnAbp.Tasks.Dtos;
using Abp.Domain.Repositories;
using AutoMapper;
using Abp.AutoMapper;
using Abp.Timing;

namespace LLR.LearnAbp.Tasks
{
    public class TaskAppService : LearnAbpAppServiceBase, ITaskAppService
    {
        private readonly IRepository<Entities.Task> _taskRepository;
        public TaskAppService(IRepository<Entities.Task> taskRepository)
        {
            _taskRepository = taskRepository;
        }

        public int CreateTask(CreateTaskInput input)
        {
            var task = new Entities.Task()
            {
                Title = input.Title,
                Description = input.Description,
                State = input.State,
                CreationTime = Clock.Now
            };
            return _taskRepository.InsertAndGetId(task);
        }

        public void DeleteTask(int taskId)
        {
            var task = _taskRepository.Get(taskId);
            if (task!=null)
            {
                _taskRepository.Delete(task);
            }
        }

        public IList<TaskDto> GetAllTasks()
        {
            return _taskRepository.GetAllList().MapTo<IList<TaskDto>>();
        }

        public TaskDto GetTaskById(int taskId)
        {
            var task = _taskRepository.Get(taskId);
            return task.MapTo<TaskDto>();
        }

        public async Task<TaskDto> GetTaskByIdAsync(int taskId)
        {
            var task = await _taskRepository.GetAsync(taskId);
            return task.MapTo<TaskDto>();
        }



        public GetTasksOutput GetTasks(GetTasksInput input)
        {
            var query = _taskRepository.GetAll();
            if (input.AssignedPersonId.HasValue)
            {
                query = query.Where(t => t.AssignedPersonId == input.AssignedPersonId.Value);
            }
            if (input.State.HasValue)
            {
                query = query.Where(t => t.State == input.State.Value);
            }

            return new GetTasksOutput()
            {
                Tasks = Mapper.Map<List<TaskDto>>(query.ToList())
            };
        }

        public void UpdateTask(UpdateTaskInput input)
        {
            Logger.Info($"Updating a task for input: {input}");
            var task = _taskRepository.Get(input.Id);
            if (input.State.HasValue)
            {
                task.State = input.State.Value;
            }

            //不需要再调用Update方法，因为应用层的方法默认是工作单元的。方法执行完成默认就自动提交
        }
    }
}
